"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : audit审计日志所占空间超过阈值
Create At   : 2021/02/18
@zou_jialiang0505328126
Description :
    1.设置数据库参数为audit_space_limit为1MB
    2.通过脚本循环重复执行DML操作，和登入登出执行操作，使pg_audit内的审计log日志大小超过1MB
    3.查看系统日志（pg_log）中是否记录空间超过阈值的事件
Expect      :
    1.设置数据库参数为audit_space_limit为1MB成功
    2.通过脚本循环重复执行DML操作，和登入登出执行操作，审计log日志大小超过1MB
    3.系统日志中记录空间超过阈值的事件
History     :
"""

import unittest
from yat.test import macro
from yat.test import Node
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class Ddldatabase(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('---Opengauss_Reliability_Dbsys_Case052.py 开始执行---')
        self.db_primary_user_node = Node(node='PrimaryDbUser')
        self.constant = Constant()

    def test_dbsys(self):
        self.log.info('---------设置数据库参数为audit_space_limit为1MB-----------')
        result = self.commonshpri.executeGsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'audit_space_limit=1MB')
        self.assertTrue(result)

        self.log.info('-----使pg_audit内的审计log日志大小超过1MB----------')
        for i in range(5000):
            result = self.commonshpri.executDbSql(r'\q')
            self.log.info(result)
            self.assertIn('', result)

        self.log.info('---查看系统日志（pg_log）中是否记录空间超过阈值的事件---')
        flag = 'WARNING:  audit file total space'
        logname = self.db_primary_user_node.sh(
            f'find "{macro.PG_LOG_PATH}" -name "*.log" -mmin -1').result()
        self.log.info(logname)
        cmd = f'cat {logname} |grep "{flag}"'
        result = self.db_primary_user_node.sh(cmd).result()
        self.log.info(result)
        self.assertIn(flag, result)


    def tearDown(self):
        self.log.info('---------恢复参数为audit_space_limit-----------')
        result = self.commonshpri.executeGsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'audit_space_limit=1GB')
        self.log.info(result)
        self.log.info('---Opengauss_Reliability_Dbsys_Case052.py 执行结束-------')
